<script setup>
import {h, onBeforeUnmount, onMounted, reactive, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
const value = ref(0)
const status=ref('订单已支付，菜品正在赶制中')
const titlestatus=ref('订单已支付，菜品正在赶制中')
const orderId=ref(1);
const tableDatas=reactive([])
const amount=ref(0)
const showdeletordersatus=ref(false)
const showcommentordersatus=ref(false)
const values=ref(1)
const routes = useRoute();
const routers=useRouter()
const comment=ref(' 我很喜欢这个菜，谢谢你')
const commentnumber=ref(0)
const isinsertcomment=ref(true)
const commentisselect=ref('green')
const centerDialogVisible=ref(false)
let intervalId;
import {ElDialog, ElInput, ElForm, ElFormItem, ElNotification} from 'element-plus';
const dialogVisible = ref(false);
import {
  Dish,
  ForkSpoon,
  Food,
  CircleCheck,

} from '@element-plus/icons-vue'
import {
  deletorderandorderdeTaliByorderIDservice,
  findorderidByuseridandnumberservice,
  findorderstatusbyorderIdservice,
  findorderstatusByuseridandnumberservice,
  findorderstatusByuseridservice, getaplyedorderaomuntbyorderIdservice,
  getaplyedorderaomuntservice,
  getaplyedorderdetaibyorderIdservice,
  getaplyedorderdetaiservice,
  insertcommentservice,

} from "@/api/food.js";



const showdiglog = () => {
  centerDialogVisible.value = true
}
const options = [
  {
    label: '已下单',
    value: 1,
    icon: Dish,
  },
  {
    label: '加工中',
    value: 2,
    icon: ForkSpoon,
  },
  {
    label: '菜品已完成',
    value: 3,
    icon: Food,
  },
  {
    label: '订单已完成',
    value: 4,
    icon:  CircleCheck,
  }

]
const getorder = async () => {

  const response=await getaplyedorderdetaibyorderIdservice(routes.query.orderId)
  console.log(routes.query.orderId)
  if(response.code===200){
    response.date.forEach(tableData => {
      tableData.isinsertcomment=true
      tableData.commentisselect='green'
      tableData.comment=''
      tableData.commentnumber=0
      tableDatas.push(tableData);
    });

  }

}
const deletorderandorderdetailByorderId = async (orderid) => {
      const response = await deletorderandorderdeTaliByorderIDservice(orderid)
      if(response.code ===200){
        centerDialogVisible.value = false
        ElNotification({
          title: 'Title',
          message: h('i', { style: 'color: teal' }, '取消订单成功'),
        })
        console.log(response.message)
        await routers.push({path:'/orderfood/orderedList'})
      }
      else {
        console.log(response.message)
      }






}
const showdeletorder=(status)=>{
  if(status.includes('完成支付')){
    showdeletordersatus.value=true
    values.value=1
    titlestatus.value='订单已支付，菜品正在赶制中'
  }
  if(status.includes('正在制作')){
    showdeletordersatus.value=true
    values.value=2
    titlestatus.value='订单已支付，菜品正在赶制中'
  }
  if( status.includes('正在配送')){
    showdeletordersatus.value=true
    values.value=3
    titlestatus.value='菜品正在赶来的路上'
  }
  if( status.includes('订单已完成')){
    showdeletordersatus.value=false
    values.value=4
    titlestatus.value='订单已完成，期待您的下一次下单'
    showcommentordersatus.value=true;
  }
}
const getamount = async () => {
  const respone=await getaplyedorderaomuntbyorderIdservice(routes.query.orderId)
  if(respone.code===200){
    amount.value=respone.date
  }
  else {
    console.log(respone.message)
  }
}
const getorderId=async ()=>{
  const response=await findorderidByuseridandnumberservice()
  if(response.code===200){
    orderId.value=response.date
  }
  else {
    console.log(respone.message)
  }
}
const getorderstatus=async ()=>{
  const response=await findorderstatusbyorderIdservice(routes.query.orderId)
  if(response.code===200){
    status.value=response.date
    showdeletorder(response.date)
  }
  else {
    console.log(response.message)
  }

}


onMounted(()=>{
  getorder()
  getamount()
  getorderId()

  intervalId = setInterval(getorderstatus, 1000); // 每5秒执行一次
})
onBeforeUnmount(() => {
  clearInterval(intervalId);
});

const submitComment = async (tableDatas) => {
  if(tableDatas !==null && tableDatas.length>0 ){
    for(let i = 0; i < tableDatas.length; i++ ){
      const tableData = tableDatas[i];
      if(tableData.isinsertcomment===true){
        await insertcommentservice(tableData.comment,tableData.commentnumber,0,tableData.id)
      }
    }


  }
  console.log('提交的评论:', comment.value);
  dialogVisible.value = false; // 关闭弹出框
};

// 新增评论按钮的点击事件
const handleCommentClick = () => {
  dialogVisible.value = true;

};
const handleCancel=()=>{

  dialogVisible.value = false;
}

const Isselectorder=async (foodItem)=>{
  foodItem.isinsertcomment=!foodItem.isinsertcomment
  if(foodItem.isinsertcomment===true){
    foodItem.commentisselect='green'
  }
  else {
    foodItem.commentisselect='grey'
  }

}
</script>


<template>
  <el-row>
    <el-col :span="24">

      <div class="grid-content ep-bg-purple-dark" id="grid-el1">
        <div>

          <el-avatar class="avatar"
                     src="https://tse2-mm.cn.bing.net/th/id/OIP-C.vTDblE86auYopAAeE2FRgwHaHa?rs=1&pid=ImgDetMain"
          />
          <span class="status">{{titlestatus}}</span>
        </div>
        <div class="order-info">

          <span class="el-order">订单号：{{routes.query.orderId}}</span>
        </div>


        <span class="thank-you">感谢您的下单</span>
      </div>
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="24"><div class="grid-content ep-bg-purple-dark" id="grid-el2" >
      <div>
        <el-segmented v-model="values" :options="options" disabled >
          <template #default="{ item }">
            <div class="flex flex-col items-center gap-2 p-2">
              <el-icon size="20">
                <component :is="item.icon" />
              </el-icon>
              <div>{{ item.label }}</div>
            </div>
          </template>
        </el-segmented>
      </div>
      <el-steps style="max-width: 600px" :active="values" align-center>
        <el-step title="已经下单" description="您已经下单成功，请耐心等待" />
        <el-step title="正在加紧加餐" description="后厨菜品正在加急加工中，请耐心等待" />
        <el-step title="已经完成菜品加工" description="菜品已经完成，请耐心等待送达" />
        <el-step title="已经完成订单" description="订单已送达，请享用" />
      </el-steps>
    </div>

    </el-col>
  </el-row>
  <el-row>
    <el-col :span="24"><div class="grid-content ep-bg-purple-dark" id="grid-el3">
      <span>已点菜品</span>

      <el-table
          :data="tableDatas"
          style="width: 100%"

      >
        <el-table-column
            prop="imageUrl"
            label="图片"
            width="180">
          <template #default="{ row }">
            <el-image
                v-if="row.imageUrl"
                :src="row.imageUrl"
                fit="cover"
                style="width: 50%; height: 50%;">
              <div slot="error" class="image-slot">
                图片加载失败
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
            prop="itemName"
            label="菜品名称"
            width="180"
        >
        </el-table-column>
        <el-table-column
            prop="quantity"
            label="数量">
        </el-table-column>
        <el-table-column
            prop="price"
            label="价格">
        </el-table-column>


      </el-table>
      <div class="total-price">
        <span>总价：￥</span>
        <span>{{amount}}</span>
      </div>
      <div class="order-button">
        <el-button type="primary" v-if="showcommentordersatus" @click="handleCommentClick">评论</el-button>
        <el-button type="primary" v-if="showdeletordersatus" @click="showdiglog">取消订单</el-button>
      </div>

    </div>
    </el-col>
  </el-row>
  <el-dialog
      title="评论订单"
      v-model="dialogVisible"
      width="30%"
      :before-close="handleCancel"
  >
    <el-form>
      <span class="comment-title">选择你要评论的菜品</span>
      <el-card
          v-for="(foodItem, foodIndex) in tableDatas"
          :key="foodIndex"
          class="card-item"
      >
        <h2 class="card-title-item">{{ foodItem.itemName }}</h2>

        <el-icon :color="foodItem.commentisselect" size="30px" class="card-icon">
          <CircleCheck @click="Isselectorder(foodItem)"   class="check-icon" />
        </el-icon>
        <img :src="foodItem.imageUrl" style="width: 20%" />
        <p class="card-price">¥: {{ foodItem.price }}</p>
        <el-form-item label="评论">
          <el-input
              v-model="foodItem.comment"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
              placeholder="请留下您的评价"
          />
        </el-form-item>
        <el-rate
            v-model="foodItem.commentnumber"
            :texts="['口味很差', '口味很一般', '口味一般', '口味很好', '口味非常好']"
            show-text
        />
      </el-card>



    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="submitComment(tableDatas)">提交</el-button>
    </span>
  </el-dialog>
  <el-dialog
      v-model="centerDialogVisible"
      title="Warning"
      width="500"
      align-center
  >
    <span>如果确认退款,则该订单将取消,请谨慎操作</span>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="centerDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="deletorderandorderdetailByorderId(routes.query.orderId)">
          确认退款
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
#grid-el1{
  background-color: wheat;
  height: 200px;
}
#grid-el2{
  background-color: wheat;
  height: 200px;
}

#grid-el3{
  background-color: wheat;
  height: 400px;
}

.grid-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 20px;
}

.ep-bg-purple-dark {
  background-color: #4B0082; /* 深紫色 */
}

.avatar-container {
  position: relative;
  margin-bottom: 10px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
}

.status {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  background-color: rgba(0, 0, 0, 0.6);
  padding: 3px 10px;
  border-radius: 5px;
  margin-bottom: 10px;
}

.order-info {
  margin-top: 20px;
  font-size: 16px;
  margin-bottom: 10px;
}

.thank-you {
  font-size: 18px;
  font-weight: bold;
}

.comment-title{
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  margin-top: 10px;
  color: #4B0082;
}
.card-title-item{
  font-size: 18px;
  font-weight: bold;
  margin-left: 25px;
}
</style>


